<?php

namespace app\socket\types;

use app\socket\object\Game;

/**
 * 五子棋房间日志
 * @property array $items 记录
 * @property string $roomId 房间号
 */
class FcLog extends Game
{
    public $pk = "roomId";
    public $cacheKey = ["swoole", "room", "log"];
    public $hidden = ['items'];
    public $type = [
        'items' => 'array'
    ];

    public function __construct($roomId = null)
    {
        if ($roomId) {
            $this->roomId = $roomId;
        }
    }

    /**
     * 记录一条日志
     *
     * @param Fcplayer $player
     * @param int $index
     * @return void
     */
    public function log($player, $index)
    {
        $key = implode(":", array_merge($this->cacheKey, [$this->roomId]));
        $value = [
            "fd" => $player->fd,
            "camp" => $player->camp,
            "index" => $index
        ];
        $this->redis->RPUSH($key, json_encode($value));
        return $this;
    }

    public function remove($num = 1)
    {
        $key = implode(":", array_merge($this->cacheKey, [$this->roomId]));
        $this->redis->LTRIM($key, 0, - ($num + 1));
    }

    /**
     * 房间日志
     *
     * @param string $roomId 房间号
     * @return FcLog
     */
    public static function find($roomId)
    {
        $class = get_called_class();
        $obj = new $class;
        $key = implode(":", array_merge($obj->cacheKey, [$roomId]));
        $logs = $obj->redis->LRANGE($key, 0, -1) ?: [];
        if (count($logs)) {
            $logs = array_map(function ($item) {
                return json_decode($item, true);
            }, $logs);
        }
        $obj->items = $logs;
        return $obj;
    }

    /**
     * 获取最后三条记录
     *
     * @return void
     */
    public function getLastThree()
    {
        $key = implode(":", array_merge($this->cacheKey, [$this->roomId]));
        $logs = $this->redis->LRANGE($key, -3, -1);
        if (!$logs) return false;
        return array_map(function ($item) {
            return json_decode($item, true);
        }, $logs);
    }
}
